package com.loongtech.bi.manager.system;

import com.loongtech.bi.dao.CommonDao;
import com.loongtech.bi.entity.POJO.PojoProjectFunction;
import com.loongtech.bi.entity.system.EntitySysUserRole;
import com.loongtech.bi.entity.system.UrlClass;
import com.loongtech.core.jpa.manager.ManagerBase;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service("sysUserRoleManager")
public class SysUserProjectRoleManager extends ManagerBase<EntitySysUserRole> {
    private static final long serialVersionUID = 7L;
    @Resource
    private CommonDao commonDao;

    public UrlClass getUrl(int u, int p, int f) {
        String sql = "select p.projectUrl, fu.src, fu.name, f.filter1, f.filterVal1, f.filter2, f.filterVal2, f.filter3, f.filterVal3 " +
                "from system_user_role r, system_function fu,system_role_function f ,system_project p " +
                "where fu.id = f.functionId and r.roleId = f.roleId and r.projectId= p.id and r.userId = ? and  r.projectId=? and f.functionId= ?";
        UrlClass result = commonDao.queryObj(sql, new Object[]{u, p, f}, UrlClass.class);
        return result;
    }

    //u为空查全部，不为空查某个用户
    public Map<String, Map<String, Set<String>>> getAllprojectsAllpages(Integer u) {
        String sql = u == null ? "select r.projectId, fu.modelId, f.functionId, p.sortId from system_user_role r, system_role_function f, system_function fu, system_project p where f.functionId = fu.id and r.roleId = f.roleId and p.id = r.projectId order by p.sortId  "
                : "select r.projectId, fu.modelId, f.functionId, p.sortId from system_user_role r, system_role_function f, system_function fu, system_project p where f.functionId = fu.id and r.roleId = f.roleId and r.userId = ?  and p.id = r.projectId order by p.sortId  ";
        List<PojoProjectFunction> pojos = commonDao.queryObjList(sql, u == null ? null : new Object[]{u}, PojoProjectFunction.class);
        Map<String, Map<String, Set<String>>> res = new LinkedHashMap<>();
        for (PojoProjectFunction pojo : pojos) {
            String pidStr = pojo.getSortId() + "-" + pojo.getProjectId();
            String midStr = pojo.getModelId() + "";
            Map<String, Set<String>> m = res.get(pidStr);
            if (m == null) {
                m = new LinkedHashMap<>();
                res.put(pidStr, m);
            }
            Set<String> s = m.get(midStr);
            if (s == null) {
                s = new LinkedHashSet<>();
                m.put(midStr, s);
            }
            s.add(pojo.getFunctionId() + "");
        }

        /*String sss = com.alibaba.fastjson.JSONArray.toJSONString(res);
        System.out.println("sssssssssssssssss " + sss);*/

        return res;
    }
}
